<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>

        <div class="filter-item">
            <label for="">班组名称：</label>
            <el-input
                v-model="searchForm.teamName"
                placeholder="请输入班组名称"
                style="width: 155px"
            />
        </div>
        <div class="filter-item">
            <label for="">排班类型：</label>
            <el-select
                v-model="searchForm.planType"
                class="m-2"
                placeholder="请选择排班类型"
                style="width: 170px"
            >
                <el-option
                    v-for="item in classesTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="search">查询</el-button>
        </div>
        <div class="filter-item">
            <el-button type="primary" @click="reset">重置</el-button>
        </div>
    </div>

    <div class="filter">
        <div class="filter-item">
            <el-button type="primary" @click="handleAdd">新增班组</el-button>
        </div>
    </div>

    <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="depId" label="所属单位">
            <template #default="scope">
                {{ depNameTranslate(scope.row.depId) }}
            </template>
        </el-table-column>
        <el-table-column prop="teamName" label="班组名称" />
        <el-table-column prop="planType" label="排班类型">
            <template #default="scope">
                {{ scope.row.planType == "1" ? "计划排班" : "自由排班" }}
            </template>
        </el-table-column>
        <el-table-column prop="teamLeaderId" label="班组长">
            <template #default="scope">
                {{ userIdTranslate(scope.row.teamLeaderId) }}
            </template>
        </el-table-column>
        <el-table-column prop="teamMembersNames" label="关联组员" />
        <el-table-column prop="comment" label="描述" />
        <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
                <el-button
                    text
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    @click="handleEditRelevance(scope.row)"
                    >关联组员</el-button
                >
                <el-button
                    text
                    type="danger"
                    size="small"
                    @click="deleteRow(scope.row)"
                    >删除</el-button
                >
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog
        v-model="addVisible"
        :title="addVisibleType == 'add' ? '新增' : '修改'"
        width="660"
    >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item label="所属单位：" prop="depId" required>
                <el-select
                    v-model="ruleForm.depId"
                    class="m-2"
                    placeholder="请选择所属单位"
                    style="width: 170px"
                    :disabled="localTypeUnit != '1'"
                >
                    <el-option
                        v-for="item in newDepIdList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="班组名称：" prop="teamName" required>
                <el-input
                    v-model="ruleForm.teamName"
                    placeholder="请输入班组"
                    style="width: 170px"
                />
            </el-form-item>

            <el-form-item label="排班类型：" prop="planType" required>
                <el-select
                    v-model="ruleForm.planType"
                    class="m-2"
                    placeholder="请选择排班类型"
                    style="width: 170px"
                >
                    <el-option
                        v-for="item in classesTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item
                label="描述："
                prop="comment"
                placeholder="请输入描述"
                style="width: 100%"
            >
                <el-input v-model="ruleForm.comment" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="relevanceVisible" title="关联组员" width="660">
        <div class="filter">
            <div class="filter-item">
                <el-input
                    v-model="relevanceSearchForm.userRealName"
                    placeholder="请输入员工姓名"
                    style="width: 155px"
                />
            </div>
            <div class="filter-item">
                <el-button type="primary" @click="handleRelevanceSearch"
                    >查询</el-button
                >
            </div>
            <div class="filter-item">
                <el-button type="warning" @click="handleddRelevance"
                    >新增关联</el-button
                >
            </div>
        </div>
        <el-table :data="relevanceList" style="width: 100%">
            <el-table-column type="index" label="序号" width="55" />
            <el-table-column prop="realName" label="员工姓名" />
            <el-table-column prop="username" label="账号" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="isTeamLeader" label="是否班组长" />
            <el-table-column fixed="right" label="操作" min-width="50">
                <template #default="scope">
                    <el-button
                        link
                        type="danger"
                        size="small"
                        @click="handleDeleteRelevance(scope.row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="relevanceVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="addRelevanceVisible" title="新增关联" width="800">
        <div style="margin: -20px 20px 0">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="grid-content">
                        <label for="">所属班组：</label>
                        <span>{{ currentRelevanceItem.teamName }}</span>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="classTitle">请选择人员</div>
        <el-transfer
            v-model="transfervalue"
            :props="{
                key: 'value',
                label: 'desc',
            }"
            filterable
            :left-default-checked="[]"
            :right-default-checked="transfervalue"
            :titles="['可选人员', '已选人员']"
            :data="tansferdata"
            @change="handleChange"
        />
        <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
                <div class="grid-content">
                    <label for="">设置班组长：</label>
                    <el-select
                        v-model="teamLeaderGood"
                        placeholder="请选择"
                        clearable
                        style="width: 160px"
                    >
                        <el-option
                            v-for="item in teamLeaderList"
                            :key="item.id"
                            :label="item.realName"
                            :value="item.id"
                        />
                    </el-select>
                </div>
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addRelevanceVisible = false">取消</el-button>
                <el-button type="primary" @click="handlesaveAddRelevance()"
                    >保存</el-button
                >
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import moment from "moment";
// api
import schedulingHttp from "@/https/scheduling.js";
import userHttp from "@/https/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
const depIdList = ref([
    { label: "全部", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const newDepIdList = ref([
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const classesTypeList = ref([
    { label: "计划排班", value: "1" },
    { label: "自由排班", value: "2" },
]);
const depNameTranslate = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (item.value == depId) {
            depName = item.label;
        }
    });
    return depName;
};
let searchForm = reactive({
    depId: "",
    teamName: "",
    planType: "",
    pageNo: 1,
    pageSize: 50,
});
let ruleForm = reactive({
    depId: "",
    teamName: "",
    planType: "",
    comment: "",
});
const rules = reactive({
    depId: [
        {
            required: true,
            message: "请输入所属单位",
            trigger: "blur",
        },
    ],
    teamName: [
        {
            required: true,
            message: "请输入班组",
            trigger: "blur",
        },
    ],
    planType: [
        {
            required: true,
            message: "请选择排班类型",
            trigger: "blur",
        },
    ],
    comment: [
        {
            required: false,
            message: "请输入描述",
            trigger: "blur",
        },
    ],
});
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;
const ruleFormRef = ref();
const tableData = ref([]);
const addVisible = ref(false);
const addVisibleType = ref("add");
const relevanceVisible = ref(false);
const addRelevanceVisible = ref(false);
const deleteRow = (row) => {
    ElMessageBox.confirm(
        `是否删除该班组【班组名称：${row.teamName}】？`,
        "删除",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            schedulingHttp.workteamsDelWorkTeams({ id: row.id }).then((res) => {
                if (res.data.code == 200) {
                    ElMessage({
                        message: "删除成功",
                        type: "success",
                    });
                    search();
                } else {
                    ElMessage({
                        message: "删除失败！",
                        type: "error",
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除",
            });
        });
};

let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
// 查询班组信息
const search = async () => {
    const res = await schedulingHttp.workteamsQueryWorkTeams(searchForm);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.teamName;
            item.value = item.id;
        });
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
    }
};
const reset = () => {
    searchForm.depId = localTypeUnit.value;
    searchForm.teamName = "";
    search();
};
const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (addVisibleType.value == "add") {
                schedulingHttp.workteamsAddWorkTeams(ruleForm).then((res) => {
                    if (res.data.code == 200) {
                        addVisible.value = false;
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            } else if (addVisibleType.value == "edit") {
                let params = {
                    ...ruleForm,
                    id: currentRowEdit.value.id,
                };
                schedulingHttp.workteamsUpdateWorkTeams(params).then((res) => {
                    if (res.data.code == 200) {
                        addVisible.value = false;
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            }
        } else {
            ElMessage({
                message: "提交错误",
                type: "danger",
            });
        }
    });
};

const handleAdd = async () => {
    ruleForm.depId = localTypeUnit.value == "1" ? "" : localTypeUnit.value;
    ruleForm.teamName = "";
    ruleForm.comment = "";
    ruleForm.planType = "";
    addVisible.value = true;
    addVisibleType.value = "add";
};
const currentRowEdit = ref();
const handleEdit = async (row) => {
    addVisible.value = true;
    addVisibleType.value = "edit";
    currentRowEdit.value = row;
    let params = {
        id: row.id,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await schedulingHttp.workteamsQueryWorkTeamsDetail(params);
    if (res.data.code == 200) {
        ruleForm.depId = res.data.data.depId + "";
        ruleForm.teamName = res.data.data.teamName;
        ruleForm.comment = res.data.data.comment;
        ruleForm.planType = res.data.data.planType + "";
    }
};
const relevanceList = ref([]);
const searchRelevanceList = ref([]);
const currentRelevanceItem = ref();
const relevanceSearchForm = reactive({
    userRealName: "",
});
const userList = ref([]);
let tansferdata = ref([]);
let transfervalue = ref([]);
const teamLeaderGood = ref();
const teamLeaderList = ref([]);
const generateData = () => {
    let data = [];
    userList.value.forEach((item) => {
        data.push({
            value: item.id,
            desc: item.realName,
        });
    });
    return data;
};
const userQueryUserList = async (depId) => {
    let params = {
        depId: depId,
        isDelete: 0,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await userHttp.userQueryUserList(params);
    if (res.data.code == 200) {
        userList.value = res.data.data.records;
    }
};

const userIdTranslate = (userId) => {
    let userName = "";
    userList.value.forEach((item) => {
        if (item.id == userId) {
            userName = item.realName;
        }
    });
    return userName;
};
const handleRelevanceSearch = async () => {};
watch(
    () => currentRelevanceItem,
    (val) => {
        console.log(val, "val");
        userQueryUserList(val.value.depId);
    },
    { deep: true }
);
const handleEditRelevance = (row) => {
    relevanceList.value = [];
    currentRelevanceItem.value = row;
    relevanceVisible.value = true;
    let idLeader = row.teamLeaderId || "";
    let ids = row.teamMembersIds !== null ? row.teamMembersIds.split(",") : [];
    ids.forEach((item) => {
        userList.value.forEach((m) => {
            if (item == m.id) {
                relevanceList.value.push(m);
            }
        });
    });
    relevanceList.value.forEach((item) => {
        if (item.id == idLeader) {
            item.isTeamLeader = "是";
        } else {
            item.isTeamLeader = "否";
        }
    });
    tansferdata = ref(generateData());
    let valueList = row.teamMembersIds ? row.teamMembersIds.split(",") : [];
    let valueListArr = [];
    valueList.forEach((item, index) => {
        item = parseInt(item);
        valueListArr[index] = item;
    });
    transfervalue.value = valueListArr;
    getTeamLeaderList(transfervalue.value);
    searchRelevanceList.value = JSON.parse(JSON.stringify(relevanceList.value));
};
const handleChange = (value, direction, movedKeys) => {
    transfervalue.value = value;
};
watch(transfervalue, (val) => {
    getTeamLeaderList(val);
});
const getTeamLeaderList = (val) => {
    teamLeaderList.value = [];
    val.forEach((item) => {
        userList.value.forEach((m) => {
            if (item == m.id) {
                teamLeaderList.value.push(m);
            }
        });
    });
};
// 删除班组关联人员
const handleDeleteRelevance = (row) => {
    ElMessageBox.confirm(`确认删除关联人员【${row.realName}】？`, "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            relevanceList.value.forEach((item, index) => {
                if (item.id == row.id) {
                    relevanceList.value.splice(index, 1);
                }
            });
            let teamLeaderId = "";
            let teamLeaderName = "";
            let teamMembersIdsList = [];
            let teamMembersNamesList = [];
            relevanceList.value.forEach((item, index) => {
                if (item.isTeamLeader == "是") {
                    teamLeaderId = item.id;
                    teamLeaderName = item.realName;
                }
                teamMembersIdsList.push(item.id);
                teamMembersNamesList.push(item.realName);
            });
            currentRelevanceItem.value.teamLeaderId = teamLeaderId;
            currentRelevanceItem.value.teamLeaderName = teamLeaderName;
            currentRelevanceItem.value.teamMembersIds =
                teamMembersIdsList.join(",");
            currentRelevanceItem.value.teamMembersNames =
                teamMembersNamesList.join(",");
            schedulingHttp
                .workteamsUpdateWorkTeams(currentRelevanceItem.value)
                .then((res) => {
                    if (res.data.code == 200) {
                        ElMessage({
                            message: "删除成功",
                            type: "success",
                        });
                        search();
                    }
                });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除",
            });
        });
};
// 新增关联人员
const handleddRelevance = () => {
    handleEditRelevance(currentRelevanceItem.value);
    teamLeaderGood.value = currentRelevanceItem.value.teamLeaderId;
    addRelevanceVisible.value = true;
};
// 保存关联人员
const handlesaveAddRelevance = () => {
    relevanceList.value = teamLeaderList.value;
    let teamLeaderId = "";
    let teamLeaderName = "";
    let teamMembersIdsList = [];
    let teamMembersNamesList = [];
    relevanceList.value.forEach((item, index) => {
        if (item.isTeamLeader == "是") {
            teamLeaderId = item.id;
            teamLeaderName = item.realName;
        }
        teamMembersIdsList.push(item.id);
        teamMembersNamesList.push(item.realName);
    });
    currentRelevanceItem.value.teamLeaderId = teamLeaderGood.value;
    currentRelevanceItem.value.teamLeaderName = teamLeaderName;
    currentRelevanceItem.value.teamMembersIds = teamMembersIdsList.join(",");
    currentRelevanceItem.value.teamMembersNames =
        teamMembersNamesList.join(",");
    schedulingHttp
        .workteamsUpdateWorkTeams(currentRelevanceItem.value)
        .then((res) => {
            if (res.data.code == 200) {
                ElMessage({
                    message: "关联成功",
                    type: "success",
                });
                handleEditRelevance(currentRelevanceItem.value);
                search();
            }
        });
    addRelevanceVisible.value = false;
};
onMounted(() => {
    userQueryUserList("");
    search();
});
</script>

<style scoped lang="less">
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}

.grid-content {
    line-height: 2;
}
.classTitle {
    margin: 20px 0;
    font-size: 16px;
    padding-left: 10px;
    border-left: 2px solid #409eff;
}
.el-transfer {
    display: flex;
    flex-direction: row;
    align-items: center;
}
:deep .el-transfer-panel {
    width: 300px;
}
:deep .el-transfer__buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
}
:deep .el-transfer__button:nth-child(2) {
    margin: 10px 0;
}
</style>